//! @Author: DengLibin
//! @Date: Create in 2023-11-07 08:58:18
//! @Description: 中间件
use axum::{
    body::Body,
    extract::DefaultBodyLimit,
    http::{HeaderValue, Request},
    middleware::{self, Next},
    response::Response,
    Router,
};
use log::debug;

pub mod auth;
pub mod timing;

/// @Author: DengLibin
/// @Date: Create in 2024-07-17 14:27:10
/// @Description: 注册中间件
pub async fn register_middleware(router: Router) -> Router {
    //中间件 照添加顺序，后添加的最先进来最后出去
    //禁用requestbody大小限制(上传大文件)
    let mut router = router.layer(DefaultBodyLimit::disable());

    router = router.layer(middleware::from_fn(my_middleware));
    //用户验证
    router = router.layer(middleware::from_fn(auth::auth));
    //计时
    router = router.layer(middleware::from_fn(timing::timing));

    router
}

/// @Author: DengLibin
/// @Date: Create in 2023-11-07 09:02:49
/// @Description: 自定义中间件
pub async fn my_middleware(request: Request<Body>, next: Next) -> Response {
    // do something with `request`...
    // let o = request.headers().get("User-Agent");
    // if let Some(header_value) = o {
    //     if let Ok(s) = header_value.to_str() {
    //         debug!("User-Agent:{}", s);
    //     }
    // }

    debug!("-------------------------->middleware:my_middleware start");
    let mut response = next.run(request).await;
    let now_time = my_util_lib::date::get_chrono_local_now_time_str();
    let r = HeaderValue::from_str(&now_time);
    if let Ok(time) = r {
        //修改响应头的Date值
        response.headers_mut().insert("Date", time);
    }

    debug!("-------------------------->middleware:my_middleware end");
    // do something with `response`...
    // let o = response.headers().get("Content-Type");
    // if let Some(header_value) = o {
    //     if let Ok(s) = header_value.to_str() {
    //         debug!("response Content-Type:{}", s);
    //     }
    // }

    response
}
